package com.example.demo.task;

import com.example.demo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @author BeauFang
 * Date: 2020/9/10
 * 容器启动完成之后，执行周期性的订单检查
 */
@Slf4j
@Component
public class OrderTask implements ApplicationListener<ApplicationStartedEvent> {
    @Autowired
    private OrderService orderService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        executor.scheduleAtFixedRate(() -> {
                    int count = orderService.updateOrderState(System.currentTimeMillis() - 10 * 1000);
                    log.info("{} 个订单未支付超时，已取消，重新补充秒杀库存", count);
                    if (count > 0) {
                        // 超时未支付的订单，重新补充进库存
                        redisTemplate.opsForValue().increment("phone:remain:count", count);
                    }
                },
                10L, 5, TimeUnit.SECONDS);
    }
}
